package com.cdvtc.forum_system.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * 增强版编码过滤器，统一处理请求和响应的UTF-8编码
 * 支持处理POST和GET请求的参数乱码问题
 */
@WebFilter(filterName = "EncodingFilter", urlPatterns = "/*")
public class EncodingFilter implements Filter {
    private String encoding = "UTF-8"; // 默认编码

    @Override
    public void init(FilterConfig config) throws ServletException {
        // 从web.xml获取配置的编码，若未配置则使用默认UTF-8
        String encodingParam = config.getInitParameter("encoding");
        if (encodingParam != null && !encodingParam.trim().isEmpty()) {
            encoding = encodingParam;
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        // 处理请求编码
        handleRequestEncoding(request);

        // 处理响应编码
        handleResponseEncoding(response);

        // 继续执行过滤器链
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 清理资源（此处无资源需要清理）
    }

    /**
     * 处理请求编码，支持POST和GET请求
     */
    private void handleRequestEncoding(ServletRequest request) {
        // 处理POST请求编码（原生支持）
        try {
            request.setCharacterEncoding(encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 处理GET请求编码（通过包装请求对象）
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            if ("GET".equalsIgnoreCase(httpRequest.getMethod())) {
                request = new Utf8GetRequestWrapper(httpRequest);
            }
        }
    }

    /**
     * 处理响应编码
     */
    private void handleResponseEncoding(ServletResponse response) {
        if (!response.isCommitted()) {
            // 设置响应内容类型和编码
            response.setContentType("text/html;charset=" + encoding);
            // 额外设置响应头（某些场景需要）
            response.setCharacterEncoding(encoding);
        }
    }

    /**
     * 自定义请求包装类，处理GET请求参数的UTF-8编码
     */
    private class Utf8GetRequestWrapper extends HttpServletRequestWrapper {
        public Utf8GetRequestWrapper(HttpServletRequest request) {
            super(request);
        }

        @Override
        public String getParameter(String name) {
            String value = super.getParameter(name);
            return encodeValue(value);
        }

        @Override
        public String[] getParameterValues(String name) {
            String[] values = super.getParameterValues(name);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    values[i] = encodeValue(values[i]);
                }
            }
            return values;
        }

        private String encodeValue(String value) {
            if (value == null) {
                return null;
            }
            try {
                // 先按ISO-8859-1解码，再按UTF-8编码
                return new String(value.getBytes("ISO-8859-1"), encoding);
            } catch (Exception e) {
                return value;
            }
        }
    }
}